const router = require('koa-router')()
const userService = require('../controllers/mySqlControll.js')
const utils = require('../config/utils.js')

router.prefix('/comment')

const c_time = utils.formateDate(new Date())

// 根据文章查找评论
router.post('/findComment',async(ctx,next)=>{
  const {id}=ctx.request.body
  console.log(id);
  console.log(ctx.request.body);
  
  try {
    const result=await userService.idFindComment(id)  
    ctx.body={
      code:'80000',
      data:result,
      msg:'查找成功'
    }
  } catch (error) {
    ctx.body={
      code:'80004',
      data:error,
      msg:"服务器错误"
    }
  }
  

})

// 提交评论
router.post('/submitComment',async(ctx,next)=>{
  const {userid,content,commentor,avatar}=ctx.request.body
  // console.log(ctx.request.body);
  try {
    const result=await userService.leaveComment([userid,commentor,avatar,content,c_time])
    if (result.affectedRows !== 0) {
      ctx.body={
        code:'80000',
        data:'评论成功',
        msg:'评论成功'
      }
    }else {
      ctx.body = {
        code: '80004',
        data: 'error',
        msg: '发布失败'
      }
    }
  } catch (error) {
    ctx.body={
      code:'80002',
      data:error,
      msg:'服务器异常'
    }
  }
})

// 提交二级评论
router.post('/submitSecondaryComment',(ctx,next)=>{
  const {name,replierName,replierContent,replierAvatar,commentId}=ctx.request.body
  // console.log(ctx.request.body);
  try {
   const result= userService.leaveSecondaryComment([name,replierName,replierContent,replierAvatar,commentId,c_time])
    if (result.affectedRows !== 0) {
      ctx.body={
        code:'80000',
        data:'评论成功',
        msg:'评论成功'
      }
    }else {
      ctx.body = {
        code: '80004',
        data: 'error',
        msg: '发布失败'
      }
    }
  } catch (error) {
      ctx.body = {
        code: '80004',
        data: error,
        msg: '服务器异常'
      }
    }
})

// 查找二级评论
router.post('/findSubmitSecondaryComment',async(ctx,next)=>{
  const {commentId}=ctx.request.body
  try {
    const result= await userService.findLeaveSecondaryComment(commentId)
    if (result) {
      ctx.body={
        code:'80000',
        data:result,
        msg:'查找成功'
      }
    }else{
      ctx.body={
        code:'80004',
        data:'error',
        msg:'失败'
      }
    }
  } catch (error) {
    ctx.body={
      code:'80002',
      data:error,
      msg:'服务器异常'
    }
  }
})


module.exports = router